package nickthissen.iracing.activities;

import java.util.ArrayList;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import nickthissen.iracing.adapters.RecentThreadListAdapter;
import nickthissen.iracing.common.Cache;
import nickthissen.iracing.common.DataLoader;
import nickthissen.iracing.common.ServiceLogging;
import nickthissen.iracing.common.Error;
import nickthissen.iracing.common.Sharing;
import nickthissen.iracing.common.Task;
import nickthissen.iracing.datamodels.RecentThread;
import nickthissen.iracing.datamodels.Result;
import nickthissen.iracing.iracingforum2.R;
import nickthissen.iracing.networking.Networking;
import nickthissen.iracing.parsing.RecentPopularParser;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class RecentPopularActivity extends TaskItemListActivity<RecentThread>
{
	private static final String TYPE = "TYPE";
	
	public static final int RECENT = 0;
	public static final int POPULAR = 1;

    private ArrayList<RecentThread> threads;
	private int type;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recentthreadlist);  

        Bundle extras = savedInstanceState;
        if (extras == null)
        {
            Intent i = this.getIntent();
            extras = i.getExtras();
        }
        type = extras.getInt(TYPE);
        
        // Set title
        ActionBar actionBar = this.getSupportActionBar();
        if (type == POPULAR) {
        	actionBar.setTitle("Popular threads");
        } else {
        	actionBar.setTitle("Recent threads");        	
        }
        
        // Start loading
    	this.loadData();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getSupportMenuInflater().inflate(R.menu.recentfavorite, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
            case R.id.mnuRefresh:
                this.loadData();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected Task<?> createTask()
    {
        return new Task<Integer>(this, loader);
    }

    @Override
    protected void saveTaskInput(Bundle state)
    {
        state.putInt(TYPE, type);
    }

    @Override
    protected Object restoreTaskInput(Bundle state)
    {
        return state.getInt(TYPE);
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        outState.putInt(TYPE, type);
        super.onSaveInstanceState(outState);
    }

    @Override
	public void onRestoreInstanceState(Bundle state)
	{
		type = state.getInt(TYPE);
		super.onRestoreInstanceState(state);
	}
	
	public static Intent getIntent(Context context, int type)
	{
		Intent i = new Intent(context, RecentPopularActivity.class);
		i.putExtra(TYPE, type);
		return i;
	}

    @Override
    protected void loadData()
    {
        boolean shouldLoadInBackground;
        ArrayList<RecentThread> cached = Cache.loadRecentPopular(type);
        if (cached != null)
        {
            threads = cached;
            setItems(threads);
            shouldLoadInBackground = true;
        }
        else
        {
            shouldLoadInBackground = false;
        }

        this.loadThreads(shouldLoadInBackground);
    }

	private void loadThreads(boolean background)
	{
        this.startLoading("Loading threads...", type, background);

        String url = type == POPULAR ? Networking.POPULAR_URL : Networking.RECENT_URL;
        ServiceLogging.logPageRequest(this, url);
	}

	@Override
	protected void setItems(ArrayList<RecentThread> items)
    {
        RecentThreadListAdapter adapter;
        if (this.getListAdapter() == null)
        {
            adapter = new RecentThreadListAdapter(this, R.layout.recentthreadrow, items);
            this.setListAdapter(adapter);
        }
        else
        {
            adapter = (RecentThreadListAdapter) this.getListAdapter();
            adapter.clear();
            for (RecentThread item : items)
            {
                adapter.add(item);
            }
        }
    }

	@Override
    public void onItemClicked(RecentThread item)
    {
        this.onItemClicked(item, false);
    }

	public void onItemClicked(RecentThread item, boolean latestReply)
    {
        this.openThread(item, latestReply);
	}

    private void openThread(RecentThread thread, boolean latestReply)
    {
        Intent intent = ThreadActivity.getIntent(this, thread, thread.ForumId, latestReply);
        this.startActivityForResult(intent, 0);
    }

    private DataLoader<Integer> loader = new DataLoader<Integer>()
    {
        @Override
        public Result getData(Integer in)
        {
            Result result = Networking.getRecentPopular(this.getContext(), in);
            if (result.Success)
            {
                String source = (String)result.Object;
                return new RecentPopularParser().parse(source);
            }
            else
            {
                return result;
            }
        }

        @Override
        public void onFinished(Result out)
        {
            if (out.Success)
            {
                threads = (ArrayList<RecentThread>)out.Object;
            }
            else
            {
                threads = new ArrayList<RecentThread>();
                Error.fromResult(out).report(this.getContext());
            }

            setItems(threads);
            Cache.saveRecentPopular(threads, type);
            finishedLoading();
        }
    };
}
